import React, { useState, useContext } from "react";
import { fileWeb } from "../../api/query";
import queryApi from "../../api/query";
import { AMAZON_URL } from "../../api/query";
import { useFocusEffect } from "@react-navigation/native";
import MaterialContext from "../../context/suppiler/materialContext";
import FormContext from "../../context/user/formContext";
import { uploadFileByS3, deleteFileByS3 } from "../../utils/s3FileUpload";
import {
  View,
  StyleSheet,
  Text,
  Image,
  Modal,
  Alert,
  TouchableWithoutFeedback,
  TouchableOpacity,
} from "react-native";
import * as ImagePicker from "expo-image-picker";

const PhotoingScreen = ({ navigation }) => {
  const { material } = useContext(MaterialContext);
  const { addAllData } = useContext(FormContext);
  // console.log("材料-----", material);

  const [imageUri, setImageUri] = useState("");
  const [isVisible, setIsVisible] = useState(true);

  useFocusEffect(
    React.useCallback(() => {
      setIsVisible(true);
    }, [])
  );

  let errMaterial = "";

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageUri(result.uri);
      // console.log(result.uri);
      setIsVisible(false);
      // console.log(result.uri);
    }
  };

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageUri(result.uri);
      setIsVisible(false);
    }
    // console.log(result);
  };

  const selectMaterial = (type) => {
    // console.log("进来---", type);
    for (let i = 0; i < material.length; i++) {
      let types = material[i].types;
      for (let j = 0; j < types.length; j++) {
        // console.log("材料---", types[j].type);
        if (types[j].type == type) {
          // console.log({
          //   category: [i, material[i].category],
          //   type: [j, type],
          // });
          return {
            category: [i, material[i].category],
            type: [j, type],
          };
        }
      }
    }
    errMaterial = errMaterial + type + ",";
    return false;
  };

  const uploadPhoto = async () => {
    // let formData = new FormData();
    // formData.append("file", {
    //   name: imageUri.split("/").pop(),
    //   uri: imageUri,
    //   type: "image/" + imageUri.split(".").pop(),
    // });
    // let res = await fetch(fileWeb + "/upload/", {
    //   method: "post",
    //   headers: {
    //     "Content-Type": "multipart/form-data",
    //   },
    //   body: formData,
    // });
    // let response = await res.json(); // if you do not use the await,you are logging the promise before it resolves
    // console.log("返回来的数据~", response.message);
    // let resUri = response.message.filePath;
    try {
      const imageUrl = await uploadFileByS3(imageUri);
      const reqUri = AMAZON_URL + "/" + imageUrl;

      const imgData = await queryApi.post("/table", { url: reqUri });
      const imageData = imgData.data.newdata;
      // console.log(imageData);

      let Result = [];
      for (let i = 0; i < imageData.length; i++) {
        let queryData = imageData[i];
        let proData = {
          type: "",
          detail: {
            specs: {
              shape: [1, ""],
              length: ["0", 2],
              width: ["0", 2],
              radius: ["0", 2],
            },
            basePlate: {
              category: [1, ""],
              thickness: ["", 2],
              type: [0, ""],
            },
            shroudPlate: {
              category: [0, ""],
              thickness: ["", 2],
              type: [1, ""],
            },
            amount: "",
          },
        };
        if (queryData[0] == "circle") {
          let basePlate = selectMaterial(queryData[4]);
          let shroudPlate = selectMaterial(queryData[5]);
          if (basePlate && shroudPlate) {
            proData.detail.specs.shape = [1, "圆形"];
            proData.detail.specs.radius[0] = queryData[3] / 2.0;
            proData.detail.basePlate.thickness[0] = queryData[1];
            proData.detail.basePlate.category = basePlate.category;
            proData.detail.basePlate.type = basePlate.type;
            proData.detail.shroudPlate.thickness[0] = queryData[2];
            proData.detail.shroudPlate.category = shroudPlate.category;
            proData.detail.shroudPlate.type = shroudPlate.type;
            proData.type = basePlate.category[1] + shroudPlate.category[1];
            proData.detail.amount = queryData[6];
            Result.push(proData);
          }
        } else if ((queryData[0] = "rectangle")) {
          let basePlate = selectMaterial(queryData[5]);
          let shroudPlate = selectMaterial(queryData[6]);
          if (basePlate && shroudPlate) {
            proData.detail.specs.shape = [0, "长方形"];
            proData.detail.specs.length[0] = queryData[3];
            proData.detail.specs.width[0] = queryData[4];
            proData.detail.basePlate.thickness[0] = queryData[1];
            proData.detail.basePlate.category = basePlate.category;
            proData.detail.basePlate.type = basePlate.type;
            proData.detail.shroudPlate.thickness[0] = queryData[2];
            proData.detail.shroudPlate.category = shroudPlate.category;
            proData.detail.shroudPlate.type = shroudPlate.type;
            proData.type = basePlate.category[1] + shroudPlate.category[1];
            proData.detail.amount = queryData[7];
            Result.push(proData);
          }
        }
      }
      // console.log("结果----", Result);
      if (errMaterial != "") {
        Alert.alert(
          "提示！",
          "暂不支持对材料" + errMaterial + "的查询,将为您继续查询其他商品!"
        );
      }
      addAllData(Result);
      navigation.navigate("Form");
      await deleteFileByS3(imageUrl);
    } catch (error) {
      console.log(error);
    }

    // console.log(imageData);
    // const imageData = [
    //   ["rectangle", "10", "6", "26", "12", "QF87", "tong3", "2"],
    //   ["rectangle", "20", "2", "16", "15", "1111", "1222", "3"],
    //   ["circle", "3", "6", "41", "QF87", "1222", "4"],
    //   ["rectangle", "7", "6", "29", "11", "8888", "8888", "6"],
    //   ["circle", "5", "7", "38", "QF87", "SF12", "5"],
    //   ["rectangle", "12", "12", "13", "10", "QF87", "tong3", "7"],
    // ];
  };

  return (
    <View>
      {imageUri != "" ? (
        <View>
          <View>
            <TouchableOpacity
              onPress={() => {
                // reSelect();
                setIsVisible(true);
              }}
            >
              <Image
                source={{ uri: imageUri }}
                style={{
                  width: "100%",
                  height: 300,
                  marginTop: 20,
                  marginRight: 10,
                  marginBottom: 10,
                  position: "relative",
                  resizeMode: "contain",
                }}
              />
            </TouchableOpacity>
          </View>
          <View style={{ alignItems: "center" }}>
            <Text style={{ fontSize: 12, color: "#888" }}>
              单击图片重新选择
            </Text>
          </View>
        </View>
      ) : null}
      <View
        style={{
          height: 45,
          width: 150,
          marginTop: 100,
          alignSelf: "center",
        }}
      >
        {imageUri == "" ? (
          <TouchableOpacity
            style={styles.confirm}
            onPress={() => {
              setIsVisible(true);
            }}
          >
            <Text style={styles.confirmText}>选择图片</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity
            style={styles.confirm}
            onPress={() => {
              uploadPhoto();
            }}
          >
            <Text style={styles.confirmText}>开始识别</Text>
          </TouchableOpacity>
        )}
      </View>

      <Modal animationType="fade" transparent={true} visible={isVisible}>
        <View style={styles.ModalBackground}></View>
        <TouchableWithoutFeedback
          onPress={() => {
            setIsVisible(false);
          }}
        >
          <View style={styles.ModalTop}></View>
        </TouchableWithoutFeedback>
        <View style={styles.ModalStyle}>
          <TouchableOpacity
            style={styles.modalOption}
            onPress={() => {
              openCamera();
            }}
          >
            <Text style={styles.modalText}>拍摄</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.modalOption, { borderBottomWidth: 4 }]}
            onPress={() => pickImage()}
          >
            <Text style={styles.modalText}>从相册选择</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.modalOption}
            onPress={() => {
              setIsVisible(false);
            }}
          >
            <Text style={styles.modalText}>取消</Text>
          </TouchableOpacity>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  modalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  confirm: {
    borderRadius: 5,
    flex: 7,
    padding: 10,
    backgroundColor: "#51bfe5",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default PhotoingScreen;
